package com.cn.why.film.filmindex.face.io;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * nio的测试，复制文件
 */
public class NioFaceAndQuickFormat {
    public static void main(String[] args) throws IOException, InterruptedException {
        //Nio测试
        Long a = System.currentTimeMillis();
        nioCopy();
        Long b = System.currentTimeMillis();
        System.out.println("nio执行时间："+(b-a));
        //io缓冲流测试
        Long c = System.currentTimeMillis();
        ioCopy();
        Long d = System.currentTimeMillis();
        System.out.println("io缓冲流执行时间："+(d-c));
    }

    /**
     * nio简单练习(适用于高并发的情况)
     */
    private static void nioCopy() throws IOException {
        String inFile = "C:\\Users\\mrzsping\\Desktop\\3333.txt";
        String outFile = "C:\\Users\\mrzsping\\Desktop\\1111.txt";
        //获取源文件和目标文件的输入输出流
        FileInputStream in = new FileInputStream(inFile);
        FileOutputStream out = new FileOutputStream(outFile);
        //获取输入输出通道
        FileChannel fileIn = in.getChannel();
        FileChannel fileOut = out.getChannel();
        //创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true){
            //清空重设缓冲区，使它可以接收读入的数据
            buffer.clear();
            //写数据进缓冲区
            int a = fileIn.read(buffer);
            if(a==-1){
                break;
            }
            buffer.flip();
            //从输出通道中将数据写入缓冲区中
            fileOut.write(buffer);
        }
    }

    /**
     * Io缓冲流测试
     */
    private static void ioCopy() throws IOException {
        //创建输入输出流
        FileReader r = new FileReader("C:\\Users\\mrzsping\\Desktop\\3333.txt");
        FileWriter w = new FileWriter("C:\\Users\\mrzsping\\Desktop\\2222.txt");
        //创建缓冲流
        BufferedReader reader = new BufferedReader(r);
        BufferedWriter writer = new BufferedWriter(w);
        //创建一个字符数组，一次读写一个字符数组
        char[] chars = new char[1024];
        int len;
        //规定大小的读取流数据
        while ((len=reader.read(chars))!=-1){
            writer.write(chars,0,len);
        }
        writer.close();
        reader.close();
    }
}
